<template>
  <div class="home-container">
    <!-- 返回按钮 -->
    <button @click="goBack" class="back-button">返回</button>
    <!-- 标题 -->
    <div class="header-banner">
      <h2 class="welcome-title">欢迎来到健康管理系统</h2>
      <p class="welcome-message">您已成功登录！</p>
    </div>

    <!-- 身体指标数据表单 -->
    <div v-if="!healthDataSubmitted" class="health-form-container">
      <h3 class="form-title">请输入您的身体指标数据</h3>
      <form @submit.prevent="submitHealthData" class="health-form">
        <div class="form-group">
          <label class="form-label">体重 (kg):</label>
          <input
            type="number"
            step="0.1"
            v-model="healthData.weight"
            class="form-input"
            placeholder="请输入体重"
            required
          />
        </div>
        <div class="form-group">
          <label class="form-label">血压:</label>
          <input
            type="text"
            v-model="healthData.bloodPressure"
            class="form-input"
            placeholder="请输入血压（如 120/80）"
            required
          />
        </div>
        <div class="form-group">
          <label class="form-label">心率:</label>
          <input
            type="number"
            v-model="healthData.heartRate"
            class="form-input"
            placeholder="请输入心率"
            required
          />
        </div>
        <div class="form-group">
          <label class="form-label">身高 (m):</label>
          <input
            type="number"
            step="0.01"
            v-model="healthData.height"
            class="form-input"
            placeholder="请输入身高"
            required
          />
        </div>
        <div class="form-group">
          <label class="form-label">年龄:</label>
          <input
            type="number"
            v-model="healthData.age"
            class="form-input"
            placeholder="请输入年龄"
            required
          />
        </div>
        <div class="form-group">
          <label class="form-label">备注:</label>
          <textarea
            v-model="healthData.notes"
            class="form-textarea"
            placeholder="请输入备注信息"
          ></textarea>
        </div>
        <button type="submit" class="submit-button">提交数据</button>
      </form>
    </div>

    <!-- 跳转后的新界面 -->
    <div v-if="healthDataSubmitted" class="action-container">
      <h3 class="action-title">请选择操作</h3>
      <div class="action-buttons">
        <button @click="goToDietRecords" class="action-button diet-button">
          饮食记录
        </button>
        <button @click="goToExerciseRecords" class="action-button exercise-button">
          运动记录
        </button>
        <button @click="generateHealthReport" class="action-button health-report-button">
          生成健康计划
        </button>
      </div>
      <!-- 健康计划展示区域 -->
      <div v-if="healthReport" class="health-report-content">
        <h3>健康计划</h3>
        <p><strong>计划名称:</strong> {{ healthReport.planName }}</p>
        <p><strong>每日卡路里目标:</strong> {{ healthReport.dailyCalories }} 卡路里</p>
        <p><strong>运动建议:</strong> {{ healthReport.exerciseRecommendation }}</p>
        <p><strong>饮食建议:</strong> {{ healthReport.dietRecommendation }}</p>
        <p><strong>生成时间:</strong> {{ formatDate(healthReport.createdAt) }}</p>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'Home',
  data() {
    return {
      healthDataSubmitted: localStorage.getItem('healthDataSubmitted') === 'true', // 从 localStorage 读取状态
      healthData: {
        userId: null, // 添加 userId 字段
        weight: null,
        bloodPressure: '',
        heartRate: null,
        height: null,
        age: null,
        notes: '',
      },
      healthReport: null, // 存储健康计划数据
    };
  },
  methods: {
    goBack() {
      this.$router.go(-1); // 返回上一页
    },
    async submitHealthData() {
      // 获取 userId（假设从 JWT 令牌中解析）
      const token = localStorage.getItem('jwt');
      if (!token) {
        alert('请先登录');
        this.$router.push('/login');
        return;
      }
      // 解析 JWT 令牌获取 userId（假设 JWT 中包含 userId）
      const payload = JSON.parse(atob(token.split('.')[1]));
      this.healthData.userId = payload.userId;

      try {
        const response = await axios.post(
          'http://127.0.0.1:8080/api/login/home/healthData/add', // 修改为正确的路径
          this.healthData,
          {
            headers: {
              Authorization: `Bearer ${token}`, // 手动添加 token 到请求头
            },
          }
        );

        if (response.data) {
          this.healthDataSubmitted = true; // 提交后显示新界面
          localStorage.setItem('healthDataSubmitted', 'true'); // 将状态保存到 localStorage
          alert('身体指标数据提交成功！');
        }
      } catch (error) {
        console.error('提交身体指标数据出错:', error);
        if (error.response && error.response.status === 403) {
          alert('登录已过期，请重新登录');
          this.$router.push('/login');
        } else {
          alert('提交身体指标数据出错，请稍后重试');
        }
      }
    },
    goToDietRecords() {
      const token = localStorage.getItem('jwt'); // 从 localStorage 获取 token
      if (!token) {
        alert('请先登录');
        this.$router.push('/login'); // 跳转到登录页面
        return;
      }

      // 检查令牌是否过期
      const payload = JSON.parse(atob(token.split('.')[1]));
      const expirationTime = payload.exp * 1000; // 转换为毫秒
      if (Date.now() > expirationTime) {
        alert('登录已过期，请重新登录');
        this.$router.push('/login');
        return;
      }

      // 跳转到饮食记录页面
      this.$router.push('/home/diet-records');
    },

    goToExerciseRecords() {
      const token = localStorage.getItem('jwt'); // 从 localStorage 获取 token
      if (!token) {
        alert('请先登录');
        this.$router.push('/login'); // 跳转到登录页面
        return;
      }

      // 检查令牌是否过期
      const payload = JSON.parse(atob(token.split('.')[1]));
      const expirationTime = payload.exp * 1000; // 转换为毫秒
      if (Date.now() > expirationTime) {
        alert('登录已过期，请重新登录');
        this.$router.push('/login');
        return;
      }

      // 跳转到运动记录页面
      this.$router.push('/home/exercise-records');
    },

    async generateHealthReport() {
      const token = localStorage.getItem('jwt'); // 从 localStorage 获取 token
      if (!token) {
        alert('请先登录');
        this.$router.push('/login'); // 跳转到登录页面
        return;
      }

      // 检查令牌是否过期
      const payload = JSON.parse(atob(token.split('.')[1]));
      const expirationTime = payload.exp * 1000; // 转换为毫秒
      if (Date.now() > expirationTime) {
        alert('登录已过期，请重新登录');
        this.$router.push('/login');
        return;
      }

      // 获取 userId
      const userId = payload.userId;

      try {
        const response = await axios.post(
          `http://127.0.0.1:8080/api/login/home/healthReports/generate/${userId}`,
          {}, // 请求体为空
          {
            headers: {
              Authorization: `Bearer ${token}`, // 添加 JWT 到请求头
            },
          }
        );

        if (response.data > 0) {
          // 模拟生成健康计划数据
          this.healthReport = {
            planName: "健康减重计划",
            dailyCalories: 1800,
            exerciseRecommendation: "每周进行 3 次有氧运动，每次 30 分钟。",
            dietRecommendation: "增加蔬菜和蛋白质摄入，减少碳水化合物。",
            createdAt: new Date(),
          };
          alert('健康计划生成成功！');
        } else {
          alert('健康计划生成失败，请重试');
        }
      } catch (error) {
        console.error('生成健康计划出错:', error);
        alert('生成健康计划出错，请稍后重试');
      }
    },
    formatDate(date) {
      if (!date) return ''; // 处理空值
      return new Date(date).toLocaleString(); // 格式化日期
    },
  },
};
</script>

<style scoped>
/* 全局背景颜色 */
body, html {
  height: 100%;
  margin: 0;
  font-family: Arial, sans-serif;
  background-color: #e0f7e0 !important; /* 淡绿色 */
}

.home-container {
  width: 100%; /* 宽度填满整个页面 */
  height: 120vh; /* 高度填满整个视口 */
  padding: 25px; /* 增加内边距 */
  text-align: center;
  background-color: rgba(255, 255, 255, 0.9); /* 白色背景，透明度为 0.9 */
  border-radius: 10px; /* 圆角 */
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); /* 阴影 */
  background-image: url('/background-image.jpg'); /* 背景图片路径 */
  background-size: cover; /* 使背景图片覆盖整个容器 */
  background-position: center; /* 背景图片居中 */
  background-repeat: no-repeat; /* 防止背景图片重复 */
}

.welcome-title {
  font-size: 28px; /* 增大字体 */
  color: #333;
  margin-bottom: 15px;
}

.welcome-message {
  font-size: 18px; /* 增大字体 */
  color: #666;
  margin-bottom: 30px;
}

.health-form-container {
  background-color: rgba(249, 249, 249, 0.9); /* 半透明背景 */
  padding: 40px; /* 减少内边距 */
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); /* 更强的阴影 */
  max-width: 600px; /* 减小表单宽度 */
  margin: 0 auto; /* 居中显示 */
}

.form-title {
  font-size: 22px; /* 增大字体 */
  color: #333;
  margin-bottom: 20px;
}

.health-form {
  display: flex;
  flex-direction: column;
  gap: 15px; /* 减少间距 */
}

.form-group {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.form-label {
  font-size: 16px; /* 增大字体 */
  color: #555;
  margin-bottom: 8px; /* 增加间距 */
}

.form-input,
.form-textarea {
  width: 100%;
  padding: 10px; /* 减少内边距 */
  border: 1px solid #ddd;
  border-radius: 8px; /* 圆角更大 */
  font-size: 14px; /* 减小字体 */
}

.form-textarea {
  height: 100px; /* 减少高度 */
  resize: vertical;
}

.submit-button {
  background-color: #007bff;
  color: white;
  padding: 10px 20px; /* 减少内边距 */
  border: none;
  border-radius: 8px; /* 圆角更大 */
  font-size: 16px; /* 减小字体 */
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.submit-button:hover {
  background-color: #0056b3;
}

.action-container {
  margin-top: 40px; /* 增加间距 */
}

.action-title {
  font-size: 24px; /* 增大字体 */
  color: #333;
  margin-bottom: 25px; /* 增加间距 */
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 25px; /* 增加间距 */
}

.action-button {
  padding: 15px 30px;
  border: none;
  border-radius: 8px; /* 圆角更大 */
  font-size: 18px; /* 增大字体 */
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.diet-button {
  background-color: #28a745;
  color: white;
}

.diet-button:hover {
  background-color: #218838;
}

.exercise-button {
  background-color: #dc3545;
  color: white;
}

.exercise-button:hover {
  background-color: #c82333;
}

.health-report-button {
  background-color: #ffc107;
  color: black;
}

.health-report-button:hover {
  background-color: #e0a800;
}

.health-report-content {
  text-align: left;
  padding: 20px;
  background-color: rgba(249, 249, 249, 0.9); /* 半透明背景 */
  border: 1px solid #ddd;
  border-radius: 8px; /* 圆角更大 */
  margin-top: 25px; /* 增加间距 */
}

p {
  margin: 12px 0; /* 增加间距 */
}

strong {
  color: #333;
}

/* 返回按钮样式 */
.back-button {
  position: absolute;
  top: 20px;
  left: 20px;
  padding: 10px 20px;
  background-color: #6c757d;
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.back-button:hover {
  background-color: #5a6268;
}
</style>